package com.itheima.reggie.Controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.Entity.User;
import com.itheima.reggie.Service.UserService;
import com.itheima.reggie.commom.Result;
import com.itheima.reggie.commom.SMSUtils;
import com.itheima.reggie.commom.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/login")
    public Result<User> login(@RequestBody Map map,HttpSession httpSession){

        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        Object codeInSession = httpSession.getAttribute(phone);
        if (codeInSession != null && codeInSession.equals(code)){
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);
            if (user == null ){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                user.setName(phone);
                userService.save(user);
            }
            httpSession.setAttribute("user",user.getId());
            return Result.success(user);
        }
        return Result.error("error");
    }

    @PostMapping("/sendMsg")
    public Result<String> sendMes (HttpSession httpSession, @RequestBody  User user){

        String phone = user.getPhone();

        if (StringUtils.isNotEmpty(phone)){
            String code = String.valueOf(ValidateCodeUtils.generateValidateCode(4));
           // SMSUtils.sendMessage("乌龟油","SMS_461395436",phone,code);
            httpSession.setAttribute(phone,code);
            log.info(code);
            return Result.success("success");
        }
        return Result.error("error");
    }
}
